import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import App from 'layout/App.js'
import './index.less';
import { FormControl, Button, Row, Col, Icon, Modal } from 'tinper-bee';
import { searchWorkProList, editWorkPro, deleteWorkPro, addWorkPro, addWorktpl, queryWorktpl } from './workprocedure.config.js'
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate } from 'utils/config.js';
import CommonModal from './../../components/CommonModal/index.jsx';
import PresetTemplate from './../../components/PresetTemplate/index.jsx';
import AddTreeNode from './AddTreeNode.jsx';
import RenderTreeTitle from './RenderTreeTitle.jsx';
import 'nprogress/nprogress.css';
import NProgress from 'nprogress';
import Tree from 'bee-tree';
import "bee-tree/build/Tree.css";
import Switch from 'bee-switch';
import 'bee-switch/build/Switch.css';
const TreeNode = Tree.TreeNode;
let newArray = [];

export default class WorkProduct extends Component {
	constructor(props) {
		super(props);
		this.state = {
			treeData: [],
			isHover: "",
			editKey: "",
			isHaveTreeDataStatus: false,
			isAddTreeNodeStatus: false,
			item: null,
			expendKey: [],
			// chooseActiveStatus: 0,
			showModal: false,
			deleteItem: null,
			searchText: '',
			modal: false,
			callbackItem: {},
			// searchAllItem: 0,
			btnColor: '',
			isPos: [],
			size: '',
			modalContent: '',
			oneButton: false,
			PkTypeArray: [],
			showDisabled: false,
		};

	}
	init = () => {
		let _me = this;
		searchWorkProList({ 'isAjax': 1, 'ieStamp': new Date().getTime(), status: this.state.showDisabled ? 2 : 1 })
			.then(function (res) {
				if (res.data.resultCode != 'busi_ex') {
					if (res.data.result.length !== 0) {
						let data = res.data.result;
						// 加工后台数据添加 name, key, id 组件组件需要属性
						_me.loopNextData(data);
						_me.setState({
							treeData: res.data.result,
							isHaveTreeDataStatus: true
						});
					}
				} else {
					danger({ 'text': res.data.exMsg })
				}
			})
	}
	loopNextData = (data) => {
		let _me = this;
		data.forEach(function (item, index) {
			item['name'] = item.sname;
			item['key'] = item.scode;
			item['id'] = item.pkProjectType;
			item['className'] = false;
			if (item.projectTypeVOS) {
				_me.loopNextData(item.projectTypeVOS)
			}
		})
	}
	handlerAddTreeNode = () => {
		if (!this.state.modal) {
			this.setState({
				isAddTreeNodeStatus: true,
				isHaveTreeDataStatus: true,
				modal: true
			});
		}
	}
	chooseRequireTpl = () => {
		newArray = [];
		queryWorktpl({ billType: 0 }).then((res) => {
			let data = res.data.result;
			this.setState({
				showModal: true,
				size: 'sm',
				modalContent: <PresetTemplate inherData={data} savePkType={this.savePkType}></PresetTemplate>,
				oneButton: true
			});
		})
	}
	handlerChooseAddTpl = () => {
		let _me = this;
		addWorktpl(this.state.PkTypeArray).then((res) => {
			let data = res.data;
			if (data.resultCode === 'busi_ex') {
				danger({ text: '引用模版与现有档案存在名称或编码重复，请修改现有档案之后再做引用导入:  ' + data.exCode + ' ' + data.exMsg })
			} else {
				this.setState({
					showModal: false
				});
				this.init();
			}
		})
	}
	savePkType = (key) => {
		let statusJson = this.findInArr(newArray, key);
		if (statusJson.status) {
			newArray.splice(statusJson.index, 1);
		} else {
			newArray.push(key);
		}
		this.setState({
			PkTypeArray: newArray
		});
	}
	findInArr = (arr, key) => {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] === key) {
				return { status: true, index: i };
			}
		}
		return { status: false };
	}
	handlerCloseAddTreeNode = (level, flag) => {
		if (!this.state.treeData.length) {
			this.setState({
				isAddTreeNodeStatus: false,
				isHaveTreeDataStatus: false,
				modal: flag
			});
		} else {
			this.setState({
				isAddTreeNodeStatus: false,
				isHaveTreeDataStatus: true,
				modal: flag
			});
		}
	}
	handlerAdd = (payload, parent, item, callback) => {
		if (payload.name === '' || payload.code === '') {
			danger({ 'text': '项目类型信息填写不完整！' });
			return;
		}
		// 校验是否符合标准
		let codeReg = /^[a-zA-Z0-9_-]+$/i;
		if (payload.name.length > 50) {
			if (codeReg.test(payload.code)) {
				if (payload.code.length > 20) {
					danger({ 'text': '编码超过了20个字符，请精简！' });
					return;
				}
			} else {
				if (payload.code.length > 20) {
					danger({ 'text': '长度错误：编码超过了20个字符，请精简！, 内容错误：只支持英文、数字、中下划线' });
					return;
				} else {
					danger({ 'text': '内容错误：只支持英文、数字、中下划线' });
					return;
				}
			}
		} else {
			if (codeReg.test(payload.code)) {
				if (payload.code.length > 20) {
					danger({ 'text': '编码超过了20个字符，请精简！' });
					return;
				}
			} else {
				if (payload.code.length > 20) {
					danger({ 'text': '长度错误：编码超过了20个字符，请精简！, 内容错误：只支持英文、数字、中下划线' });
					return;
				} else {
					danger({ 'text': '内容错误：只支持英文、数字、中下划线' });
					return;
				}
			}
		}
		let _me = this;
		let param = { 'enableStatus': 1, 'sname': payload.name.trim(), 'scode': payload.code, 'isAjax': 1 };
		// 如果为同级添加则pkParent为父级pkParent
		if (item !== undefined && item !== null) {
			let timedPkParent = payload.isSameLevel ? { 'pkParent': item.pkParent } : { 'pkParent': item.pkProjectType };
			param = Object.assign({}, param, timedPkParent);
		}
		addWorkPro(param).
			then(function (res) {
				if (res.data.resultCode !== 'busi_ex') {
					let data = res.data.result;
					data['name'] = data.sname;
					data['key'] = data.scode;
					if (!item) {
						_me.state.treeData.push(data);
					} else {
						if (payload.isSameLevel) {
							parent['projectTypeVOS'].push(data);
						} else {
							if (!item['projectTypeVOS']) {
								item['projectTypeVOS'] = [data];
							} else {
								item['projectTypeVOS'].push(data);
							}
						}
					}
					_me.setState({
						treeData: _me.state.treeData
					}, function () {
						_me.setState({
							isHaveTreeDataStatus: true
						});
					});
					callback && callback();
				} else {
					danger({ 'text': res.data.exMsg });
				}
			})
	}
	//鼠标滑过工序行事件 
	onMouseEnter = (node) => {
		let _me = this;
		if (!_me.state.modal) {
			if (_me.state.isHover === node.node.props.title.props.item.key) {
				_me.loopNextClearClassNameData(this.state.treeData);
				_me.setState({
					isHover: '',
					isPos: node.node.props.pos.split('-'),
					callbackItem: {},
					treeData: this.state.treeData
				})
			} else {
				_me.loopNextClearClassNameData(this.state.treeData);
				_me.setState({
					isHover: node.node.props.title.props.item.key,
					isPos: node.node.props.pos.split('-'),
					callbackItem: {},
					treeData: this.state.treeData
				})
			}
		}
	}
	//鼠标离开事件 重置显隐参数
	// onMouseLeave = (node) => {
	// 	this.setState({
	// 		isHover: false
	// 	});
	// }
	loopNextClearClassNameData = (data) => {
		let _me = this;
		data.forEach(function (item, index) {
			item['className'] = false;
			if (item.projectTypeVOS) {
				_me.loopNextData(item.projectTypeVOS)
			}
		})
	}
	handlerEditCancel = (flag) => {
		this.setState({
			isHover: "",
			editKey: "",
			modal: flag
		})
	}
	handlerEditConfirm = (item, flag) => {
		let _me = this;
		let nameReg = /^\S+$/i;
		if (item.name.length === 0) {
			danger({ 'text': '请输入名称！' });
			return;
		} else {
			if (item.name.length >= 50) {
				danger({ 'text': '名称请限制在50个字符之内！' });
				return;
			}
		}
		let param = {
			'scode': item.scode,
			'sname': item.name.trim(),
			'pkProjectType': item.pkProjectType,
			'changeFlag': item.changeFlag,
			'isAjax': 1
		};
		editWorkPro(param).
			then(function (res) {
				if (res.data.resultCode !== 'busi_ex') {
					_me.init();
					// let data = res.data.result;
					// data['name'] = data.sname;
					// data['key'] = data.scode;
					// data['id'] = item.pkProjectType;
					// _me.loopNextEdit(_me.state.treeData, item, data);
					_me.setState({
						isHover: "",
						editKey: "",
						modal: flag,
						// treeData: _me.state.treeData,
						callbackItem: item
					})
				} else {
					danger({ 'text': res.data.exMsg })
				}
			})
	}
	loopNextEdit = (data, propsItem, dataItem) => {
		let _me = this;
		data.forEach(function (item, index) {
			if (item.key === propsItem.key) {
				data.splice(index, 1, Object.assign({}, dataItem, { 'projectTypeVOS': propsItem.projectTypeVOS }));
			} else {
				if (item.projectTypeVOS) {
					_me.loopNextEdit(item.projectTypeVOS, propsItem, dataItem);
				}
			}
		})
	}
	onExpand = (item, list) => {
		let itemIndex = this.state.expendKey.indexOf(list.node.props.title.props.item.key);
		let save = [];
		let saveBox = [];
		let saveItem = {};
		this.state.treeData.forEach(function (item, index) {
			if (item.key == list.node.props.title.props.item.key) {
				save.push(item.key);
				saveItem = item;
				if (item.projectTypeVOS) {
					item.projectTypeVOS.forEach(function (item, index) {
						save.push(item.key)
					})
				}
			}
		})
		if (itemIndex == -1 && list.expanded != false) {
			this.setState({
				expendKey: [list.node.props.title.props.item.key, ...this.state.expendKey]
			});
		} else {
			if (saveItem.projectTypeVOS) {
				saveBox = this.state.expendKey.filter(function (item) {
					return save.indexOf(item) == -1
				})
				this.setState({
					expendKey: saveBox
				});
			} else {
				this.state.expendKey.splice(itemIndex, 1);
				this.setState({
					expendKey: this.state.expendKey
				});
			}
		}
	}
	handlerEditRender = (item, flag) => {
		this.setState({
			editKey: item.key,
			modal: flag
		});
	}
	handlerCreateRender = (item, flag) => {
		this.state.expendKey.push(item.key)
		this.setState({
			item: item,
			expendKey: this.state.expendKey,
			modal: flag
		});
	}
	//添加同级
	handleCreateSameLevel = (item, flag) => {
		this.state.expendKey.push(item.key)
		this.setState({
			item: item,
			expendKey: this.state.expendKey,
			modal: flag
		});
	}
	handlerDeleteRender = (item) => {
		let _me = this;
		if (item.projectTypeVOS) {
			if (item.projectTypeVOS.length !== 0) {
				danger({ 'text': '此条工序为父级不能删除' });
				return;
			} else {
				_me.setState({
					showModal: true,
					deleteItem: item,
					size: 'sm',
					modalContent: '',
					oneButton: false
				});
			}
		} else {
			_me.setState({
				showModal: true,
				deleteItem: item,
				size: 'sm',
				modalContent: '',
				oneButton: false
			});
		}
	}
	handlerDelete = (item) => {
		let _me = this;
		_me.setState({
			deleteItem: item
		});
		deleteWorkPro({ 'pkProjectType': item.pkProjectType, 'changeFlag': item.changeFlag, 'isAjax': 1 }).
			then(function (res) {
				if (res.data.resultCode !== 'busi_ex') {
					_me.loopNext(_me.state.treeData);
					_me.loopNextDeleteEmptyChildren(_me.state.treeData);
					if (_me.state.treeData.length === 0) {
						_me.setState({
							treeData: _me.state.treeData,
							isHaveTreeDataStatus: false
						});
					} else {
						_me.setState({
							treeData: _me.state.treeData
						});
					}
					success({ 'text': '删除成功！' });
				} else {
					danger({ 'text': res.data.exMsg });
				}
			})
		_me.setState({
			showModal: false
		});
	}
	loopNext = (data) => {
		let _me = this;
		data.forEach(function (item, index) {
			if (item.key === _me.state.deleteItem.key) {
				data.splice(index, 1);
			} else {
				if (item.projectTypeVOS) {
					_me.loopNext(item.projectTypeVOS)
				}
			}
		})
	}
	loopNextDeleteEmptyChildren = (data) => {
		let _me = this;
		data.forEach(function (item, index) {
			if (item.projectTypeVOS) {
				if (item.projectTypeVOS.length === 0) {
					delete item.projectTypeVOS
				} else {
					_me.loopNextDeleteEmptyChildren(item.projectTypeVOS);
				}
			}
		})
	}
	componentDidMount = () => {
		this.init();
		window.addEventListener('scroll', this.handlerScrollWindow);
		document.addEventListener('click', () => {
			this.setState({
				isHover: '',
				isPos: []
			});
		});
	}
	chooseAll = (e) => {
		e.nativeEvent.stopImmediatePropagation();
	}
	handlerExpanded = (e, data) => {
		if (this.state.modal) return;
		let newExpendKey = [];
		// let type = this.state.searchAllItem || e.target.getAttribute('data-index');
		// if (type == 2) {
		// 	this.state.treeData.forEach(function (item, index) {
		// 		newExpendKey.push(item.key);
		// 	})
		// } else if (type == 3) {
		// 	this.state.treeData.forEach(function (item, index) {
		// 		newExpendKey.push(item.key);
		// 		if (item.projectTypeVOS) {
		// 			item.projectTypeVOS.forEach(function (item, index) {
		// 				newExpendKey.push(item.key);
		// 			})
		// 		}
		// 	})
		// }
		this.setState({
			expendKey: newExpendKey,
			// chooseActiveStatus: type,
			// searchAllItem: 0
		});
	}
	close = () => {
		this.setState({
			showModal: false
		});
	}
	handlerSearchValue = (e) => {
		this.setState({
			searchText: e.target.value.trim()
		});
	}
	handlerSearch = () => {
		let _me = this;
		let data = this.state.treeData;
		let spaceReg = /\s+/i;
		let keyWord = this.state.searchText;
		if (this.state.modal) return;
		if (this.state.searchText === '') {
			danger({ 'text': '请输入具体内容！' });
			return;
		}
		if (spaceReg.test(this.state.searchText)) {
			keyWord = this.state.searchText.split(/\s+/);
		} else {
			keyWord = this.state.searchText;
		}
		this.loopNextSearchData(data, keyWord);
		this.setState({
			treeData: data,
			// searchAllItem: 3
		}, function () {
			_me.handlerExpanded()
		});
	}
	loopNextSearchData = (data, keyword) => {
		let _me = this;
		if (typeof (keyword) == 'string') {
			data.forEach(function (item, index) {
				if (item.sname.indexOf(keyword) > -1 || item.scode.indexOf(keyword) > -1) {
					item['className'] = true;
				} else {
					item['className'] = false;
				}
				if (item.projectTypeVOS) {
					_me.loopNextSearchData(item.projectTypeVOS, keyword)
				}
			})
		} else {
			data.forEach(function (item, index) {
				var parentItem = item;
				var controlSme = true;
				keyword.forEach(function (item) {
					if (parentItem.sname.indexOf(item) > -1 || parentItem.scode.indexOf(item) > -1) {
						if (controlSme) {
							parentItem['className'] = true;
						}
					} else {
						parentItem['className'] = false;
						controlSme = false;
					}
				})
				if (parentItem.projectTypeVOS) {
					_me.loopNextSearchData(parentItem.projectTypeVOS, keyword)
				}
			})
		}
	}
	changeBtnColorToNone = () => {
		this.setState({
			btnColor: 'primary'
		});
	}
	changeBtnColorToParamry = () => {
		this.setState({
			btnColor: ''
		});
	}
	handlerScrollWindow = (e) => {
		if (e.target.scrollingElement.scrollTop >= 10) {
			this.refs.fixedTop.className = 'header clearfix header--fixed-top';
			this.refs.contenBox.className = 'content content--margin-top';
		} else {
			this.refs.fixedTop.className = 'header clearfix';
			this.refs.contenBox.className = 'content';
		}
	}
	hideModal = () => {
		this.setState({
			showModal: false
		});
	}
	handleClearInput = () => {
		let _me = this;
		_me.setState({
			searchText: ''
		});
	}
	onShowDisabledChange = () => {
		this.setState({
			showDisabled: !this.state.showDisabled
		}, () => {
			this.init();
		});
	}
	render() {
		let _me = this;
		const loop = (data, parent) => {
			if (!data) {
				return undefined;
			}
			return data.map((item) =>
				<TreeNode title={<RenderTreeTitle item={item}
					editKey={_me.state.editKey}
					isHover={_me.state.isHover}
					isPos={this.state.isPos}
					onCloseAddTreeNode={this.handlerCloseAddTreeNode}
					onAdd={this.handlerAdd}
					callbackItem={this.state.callbackItem}
					onEditRender={this.handlerEditRender}
					onCreateRender={this.handlerCreateRender}
					onCreateSameLevel={this.handleCreateSameLevel}
					onDeleteRender={this.handlerDelete}
					onEditCancel={this.handlerEditCancel}
					onEditConfirm={this.handlerEditConfirm}
					onEnableStatusChanged={this.init}
					parent={parent}
					className={item.className}></RenderTreeTitle>} key={item.key}>{loop(item.projectTypeVOS, item)}</TreeNode>
				// if (item !== null) {
				// }
				// return null;
			)
		};
		const treeNodes = loop(this.state.treeData);
		return (
			<App onscroll={this.handlerScrollWindow}>
				<CommonModal className="modal-position-format"
					show={this.state.showModal}
					cancel={this.close}
					confirm={this.state.oneButton ? this.handlerChooseAddTpl : this.handlerDelete}
					content={this.state.modalContent}
					backdrop={false}
					hide={this.hideModal}
					size={this.state.size}
					oneButton={this.state.oneButton}
					oneButtonText='确定'></CommonModal>
				<div className="block__product">
					<div className="header clearfix" ref="fixedTop">
						<h1 className="fl header__title">项目类型</h1>
						<div className="header__search clearfix fl">
							<label className="header__search_label">搜索 :</label>
							<FormControl className="fl header__search_input_format"
								placeholder="请输入项目类型编码、项目类型名称"
								onChange={this.handlerSearchValue}
								onFocus={this.changeBtnColorToNone}
								value={this.state.searchText}
								onBlur={this.changeBtnColorToParamry} />
							<span className="clear-input-content" onClick={this.handleClearInput}>x</span>
							<Button colors={this.state.btnColor}
								className="fl btn_style_format"
								onClick={this.handlerSearch}>
								<Icon type="uf-search-light-2"></Icon>
							</Button>
						</div>
						<Button colors="primary" className="fr header__addbtn" onClick={this.handlerAddTreeNode}>新建项目类型</Button>
						{/* <Button colors="primary" className="fr header__requirebtn" onClick={this.chooseRequireTpl}>引用预置模板</Button> */}
					</div>
					<div className="content" ref="contenBox">
						{!this.state.isHaveTreeDataStatus && <p className="content__notice">您还<span>未创建</span>项目类型档案, 请点击右上角<b> 新建项目类型 </b>按钮, 开始创建 !</p>}
						{this.state.isHaveTreeDataStatus && <div className="content__group clearfix">
							{/* <span className="fl content__group_title">展示：</span>
							<div className="group__btn fl">
								<span data-index="1" onClick={this.handlerExpanded} className={this.state.chooseActiveStatus == 1 ? 'active' : ''}>一级</span>
								<span data-index="2" onClick={this.handlerExpanded} className={this.state.chooseActiveStatus == 2 ? 'active' : ''}>二级</span>
								<span data-index="3" onClick={this.handlerExpanded} className={this.state.chooseActiveStatus == 3 ? 'active' : ''}>三级</span>
							</div> */}
							{/* <p className="fl">注：鼠标滑过工序名称，显示 <span>操作按钮</span>，另外目录只支持创建<span>3级</span>.</p> */}
							<div className="fr">
								<Switch
									checked={this.state.showDisabled}
									onChange={this.onShowDisabledChange}
									// className=""
									size='sm'
								/>
								<span className='showdisabletext'>显示停用</span>
							</div>
						</div>}
						{this.state.isHaveTreeDataStatus && <div style={{ 'width': '100%' }} onClick={this.chooseAll}>
							<div className='seperator'></div>
							<Tree onMouseLeave={this.onMouseLeave}
							onMouseEnter={this.onMouseEnter}
							openIcon={<Icon type="uf-minus" />}
							closeIcon={<Icon type="uf-plus" />}
							// expandedKeys={this.state.expendKey}
							// onExpand={this.onExpand}
						>
							{treeNodes}
						</Tree></div>}
						{this.state.isAddTreeNodeStatus && <AddTreeNode onClose={this.handlerCloseAddTreeNode}
							onAdd={this.handlerAdd}
							level={''}
						></AddTreeNode>}
					</div>
				</div>
			</App>)
	}
}
